package com.benin.sms

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.switchMap
import com.benin.sms.base.BaseViewModel
import com.benin.sms.model.RevUserNextPhoneNumber
import com.benin.sms.model.ToBase
import com.benin.sms.model.ToSavePhoneNumberStateTo
import com.benin.sms.network.RepoUserProcess
import kotlinx.coroutines.Job

class ViewModelUserStatus : BaseViewModel() {

    var mCallPhoneNumber: String = ""
    var mCallPhoneType: String = ""
    var mCallOrderId: String = ""
    var mCallUserId: String = ""
    var mCallProduct: String = ""
    var mCallCanActive: Boolean = false

    var mLastPhoneNumberIsNull: Boolean = false //是否最后一次获取的号码为空
    var mIsManualStopCalling: Boolean = false //是否手动停止拨打电话
    var mIsFetchingPhoneNumber: Boolean = false //是否正在获取号码
    var mLastValidFetchingTime: Long = 0L //上一次正在获取号码的时间
    var mLastValidRejectTime: Long = 0L //上一次正在号码挂断的时间

    var mDelayJob: Job? = null

    private val mLiveDataNextPhoneNumber = MutableLiveData<ToBase>()

    private val mLiveDataSavePhoneNumberState = MutableLiveData<ToSavePhoneNumberStateTo>()

    val LiveDataNextPhoneNumber = mLiveDataNextPhoneNumber.switchMap { query ->
        RepoUserProcess.getNextPhoneNumber(this, query)
    }

    val LiveDataSavePhoneNumberState =
        mLiveDataSavePhoneNumberState.switchMap { query ->
            RepoUserProcess.savePhoneNumberState(this, query)
        }

    fun getNextPhoneNumber(showLoading: Boolean = true) {
        if (mIsFetchingPhoneNumber) {
            return
        }
        mIsFetchingPhoneNumber = true
        mLastValidFetchingTime = System.currentTimeMillis()
        val toBase = ToBase()
        toBase.showLoading = showLoading
        mLiveDataNextPhoneNumber.value = toBase
    }

    fun savePhoneNumberState(toSavePhoneNumberStateTo: ToSavePhoneNumberStateTo) {
        mLiveDataSavePhoneNumberState.value = toSavePhoneNumberStateTo
    }

    fun updatePhoneNumberInfo(revObjUserNextPhoneNumber: RevUserNextPhoneNumber.RevObjUserNextPhoneNumber?) {
        mCallPhoneNumber = ""
        mCallPhoneType = ""
        mCallOrderId = ""
        mCallUserId = ""
        mCallProduct = ""
        mCallCanActive = false

        revObjUserNextPhoneNumber?.let { it ->
            mCallPhoneNumber = it.mobile.toString()
            mCallPhoneType = it.mobileType.toString()
            mCallOrderId = it.orderId.toString()
            mCallUserId = it.userId.toString()
            mCallProduct = it.product.toString()
        }
    }
}